package
{
	import laya.events.Event;
	import laya.net.Socket;
	import laya.utils.Byte;

	/**
	 *@date 2017-2-15 下午2:48:44
	 *@author zhouhonghui
	 */
	public class WebSocketDemo
	{
		private var _msg:Byte;
		private var _socket:Socket;
		public function WebSocketDemo()
		{
			_msg = new Byte();
			_socket = new Socket();
			
			_socket.on(Event.OPEN,this,onOpen);
			_socket.on(Event.CLOSE,this,onClose);
			_socket.on(Event.MESSAGE,this,onMsg);
			_socket.on(Event.ERROR,this,onError);
			
			_socket.connect('127.0.0.1',9999); //需要是websocket服务器才行
		}
		private function onOpen(e:*=null):void
		{
			alert(".....onOpen......");	
			var msg:String = "I am Laya!";
			//0x11 + 封包长度 + 协议号 + 数据 + 0x22 					
			/*_sock.writeShort(0x11); // h
			_sock.writeUnsignedInt(100);// I 封包长度  4个字节
			_sock.writeUnsignedInt(1001);//I 协议号    4个字节				
			_sock.writeUTF(msg); //s  
			_sock.writeUTF(msg+",追加的信息");//s
			_sock.writeShort(3)//b 注意对应C的数据类型signed char(1个字节长度) 1个字节				
			_sock.writeInt(1500);//i 4个字节 有符号整形
			_sock.writeShort(0x22);
			_sock.flush();*/
			
			/*
			
			var byte:Byte = _socket.output;
			byte.clear();*/
			//byte.endian = Byte.LITTLE_ENDIAN;
			/*byte.writeUint16(0x11);
			byte.writeUint32(100);
			byte.writeUint32(1002);
			byte.writeUTFBytes(msg);*/
			/*byte.writeUTFBytes(msg+",追加的信息");			
			byte.writeInt16(3);
			byte.writeInt32(1500);*/
			//byte.writeInt16(0x22);			
			//_socket.flush();
			_socket.send(msg);
		}
		private function onClose(e:*=null):void
		{
			alert(".....onClose......");	
		}
		private function onMsg(msg:*=null):void
		{
			alert(".....onMsg......");	
			_msg.clear();
			_msg.writeArrayBuffer(msg);
			trace(_msg.readUTFString());
		}
		private function onError(e:*=null):void
		{
			alert(".....onError......");	
		}
	}
}